# coding:utf-8
from qfluentwidgets import (SwitchSettingCard, FolderListSettingCard,
                            OptionsSettingCard, PushSettingCard,
                            HyperlinkCard, PrimaryPushSettingCard, ScrollArea,
                            ComboBoxSettingCard, ExpandLayout, Theme, CustomColorSettingCard,
                            setTheme, setThemeColor, isDarkTheme, setFont)
from qfluentwidgets import FluentIcon as FIF
from qfluentwidgets import SettingCardGroup as CardGroup
from qfluentwidgets import InfoBar, Dialog
from PySide6.QtCore import Qt, Signal, QUrl, QStandardPaths, QTimer, QProcess
from PySide6.QtGui import QDesktopServices, QFont
from PySide6.QtWidgets import QWidget, QLabel, QFileDialog, QApplication
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
import json
import os
import requests # Added for new API calls

from ..common.config import cfg, isWin11
from ..common.setting import AUTHOR, VERSION, YEAR, APP_NAME,APP_KEY,GITHUB_URL
from ..common.signal_bus import signalBus
from ..common.style_sheet import StyleSheet
from ..components.line_edit_card import LineEditSettingCard

class SettingCardGroup(CardGroup):

   def __init__(self, title: str, parent=None):
       super().__init__(title, parent)
       setFont(self.titleLabel, 14, QFont.Weight.DemiBold)



class SettingInterface(ScrollArea):
    """ Setting interface """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.scrollWidget = QWidget()
        self.expandLayout = ExpandLayout(self.scrollWidget)

        # setting label
        self.settingLabel = QLabel(self.tr("Settings"), self)

        # LLM settings
        self.llmGroup = SettingCardGroup(
            self.tr('大模型'), self.scrollWidget
        )
        self.llmNameCard = LineEditSettingCard(
            FIF.EDIT,
            self.tr('大模型名称'),
            self.tr('输入您的大模型名称'),
            cfg.llmName,
            parent=self.llmGroup
        )
        # self.llmBaseUrlCard = LineEditSettingCard(
        #     FIF.LINK,
        #     self.tr('大模型地址'),
        #     self.tr('输入您的大模型 API 地址'),
        #     cfg.llmBaseUrl,
        #     parent=self.llmGroup
        # )
        self.llmApiKeyCard = LineEditSettingCard(
            FIF.CERTIFICATE,
            self.tr('大模型密钥'),
            self.tr('输入您的大模型 API 密钥'),
            cfg.llmApiKey,
            parent=self.llmGroup
        )

        # personalization
        self.personalGroup = SettingCardGroup(
            self.tr('Personalization'), self.scrollWidget)
        self.micaCard = SwitchSettingCard(
            FIF.TRANSPARENT,
            self.tr('Mica effect'),
            self.tr('Apply semi transparent to windows and surfaces'),
            cfg.micaEnabled,
            self.personalGroup
        )
        self.themeCard = ComboBoxSettingCard(
            cfg.themeMode,
            FIF.BRUSH,
            self.tr('Application theme'),
            self.tr("Change the appearance of your application"),
            texts=[
                self.tr('Light'), self.tr('Dark'),
                self.tr('Use system setting')
            ],
            parent=self.personalGroup
        )
        self.themeColorCard = CustomColorSettingCard(
            cfg.themeColor,
            FIF.PALETTE,
            self.tr('主题颜色'),
            self.tr('更改应用主题颜色'),
            self.personalGroup
        )
        self.zoomCard = ComboBoxSettingCard(
            cfg.dpiScale,
            FIF.ZOOM,
            self.tr("Interface zoom"),
            self.tr("Change the size of widgets and fonts"),
            texts=[
                "100%", "125%", "150%", "175%", "200%",
                self.tr("Use system setting")
            ],
            parent=self.personalGroup
        )
        self.languageCard = ComboBoxSettingCard(
            cfg.language,
            FIF.LANGUAGE,
            self.tr('Language'),
            self.tr('Set your preferred language for UI'),
            texts=['简体中文', '繁體中文', 'English', self.tr('Use system setting')],
            parent=self.personalGroup
        )

        # update software
        self.updateSoftwareGroup = SettingCardGroup(
            self.tr("Software update"), self.scrollWidget)
        self.updateOnStartUpCard = SwitchSettingCard(
            FIF.UPDATE,
            self.tr('Check for updates when the application starts'),
            self.tr('The new version will be more stable and have more features'),
            configItem=cfg.checkUpdateAtStartUp,
            parent=self.updateSoftwareGroup
        )

        # application
        self.aboutGroup = SettingCardGroup(self.tr('About'), self.scrollWidget)
        
        self.aboutCard = PrimaryPushSettingCard(
            self.tr('Check update'),
            ":/app/images/logo.png",
            self.tr('About') + " " + APP_NAME,
            '© ' + self.tr('Copyright') + f" {YEAR}, {AUTHOR}. " +
            self.tr('Version') + " " + VERSION,
            self.aboutGroup
        )
        self.openSourceCard = HyperlinkCard(
            GITHUB_URL,
            self.tr('点击跳转到 Gitee 仓库'),
            FIF.GITHUB,
            self.tr('客户端开源'),
            self.tr('智拓AI客户端严格遵循qfluentwidgets框架GPL-3.0开源协议'),
            self.aboutGroup
        )

        self.__initWidget()
        self.network_manager = QNetworkAccessManager(self)
        # 应用启动时自动检查更新 (延迟执行，避免阻塞UI)
        QTimer.singleShot(1500, self.check_for_updates_on_startup)
        # 加载大模型名称
        # QTimer.singleShot(500, self.load_llm_models) # 延迟加载，避免阻塞UI太久

    def __initWidget(self):
        self.resize(1000, 800)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setViewportMargins(0, 100, 0, 20)
        self.setWidget(self.scrollWidget)
        self.setWidgetResizable(True)
        self.setObjectName('settingInterface')

        # initialize style sheet
        setFont(self.settingLabel, 23, QFont.Weight.DemiBold)
        self.scrollWidget.setObjectName('scrollWidget')
        self.settingLabel.setObjectName('settingLabel')
        StyleSheet.SETTING_INTERFACE.apply(self)
        self.scrollWidget.setStyleSheet("QWidget{background:transparent}")

        self.micaCard.setEnabled(isWin11())

        # initialize layout
        self.__initLayout()
        self._connectSignalToSlot()

    def __initLayout(self):
        self.settingLabel.move(36, 50)

        self.llmGroup.addSettingCard(self.llmNameCard)
        #self.llmGroup.addSettingCard(self.llmBaseUrlCard)
        self.llmGroup.addSettingCard(self.llmApiKeyCard)

        self.personalGroup.addSettingCard(self.micaCard)
        self.personalGroup.addSettingCard(self.themeCard)
        self.personalGroup.addSettingCard(self.themeColorCard)
        self.personalGroup.addSettingCard(self.zoomCard)
        self.personalGroup.addSettingCard(self.languageCard)

        self.updateSoftwareGroup.addSettingCard(self.updateOnStartUpCard)

        self.aboutGroup.addSettingCard(self.aboutCard)
        self.aboutGroup.addSettingCard(self.openSourceCard)

        # add setting card group to layout
        self.expandLayout.setSpacing(28)
        self.expandLayout.setContentsMargins(36, 10, 36, 0)
        self.expandLayout.addWidget(self.llmGroup)
        self.expandLayout.addWidget(self.personalGroup)
        self.expandLayout.addWidget(self.updateSoftwareGroup)
        self.expandLayout.addWidget(self.aboutGroup)

    def _showRestartTooltip(self):
        """ show restart tooltip """
        InfoBar.success(
            self.tr('Updated successfully'),
            self.tr('Configuration takes effect after restart'),
            duration=1500,
            parent=self
        )

    def _connectSignalToSlot(self):
        """ connect signal to slot """
        cfg.appRestartSig.connect(self._showRestartTooltip)

        # personalization
        cfg.themeChanged.connect(setTheme)
        self.themeColorCard.colorChanged.connect(lambda c: setThemeColor(c))
        self.micaCard.checkedChanged.connect(signalBus.micaEnableChanged)

        # check update
        self.aboutCard.clicked.connect(self.check_for_updates_interactive)

        

    def check_for_updates(self, is_interactive: bool):
        """新版：检查更新，直接请求新API"""
        try:
            response = requests.get("http://hn.api.yesapi.net/api/SVIP/Swx69106951_MyApi/AGetUpdate?app_key="+APP_KEY, timeout=8)
            response.raise_for_status()
            data = response.json()
            if data.get("ret") == 200 and data["data"].get("err_code") == 0:
                item = data["data"].get("item", {})
                latest_version = item.get("version", "N/A")
                download_url = item.get("url")
                update_log = item.get("log", self.tr('无更新说明'))

                # 比较版本号
                if latest_version != VERSION:
                    title = self.tr("发现新版本")
                    content = self.tr("检测到 {1} 有新版本（{0}），是否立即前往下载？").format(latest_version, APP_NAME)
                    if update_log:
                        content += "\n" + self.tr("更新内容:") + "\n" + update_log
                    dialog = Dialog(title, content, self.window())
                    if dialog.exec():
                        if download_url:
                            self.open_download_url(download_url)
                        else:
                            InfoBar.warning(self.tr("未找到下载链接"), self.tr("新版本的下载链接缺失。"), parent=self)
                elif is_interactive:
                    InfoBar.success(
                        self.tr("已是最新版本"),
                        self.tr("您正在使用最新版本 {0}（{1}）。").format(APP_NAME, latest_version),
                        duration=3000, 
                        parent=self
                    )
            else:
                msg = data.get("msg", "服务器返回未知错误。")
                if is_interactive:
                    InfoBar.error(self.tr("检查更新失败"), msg, parent=self)
                print(f"检查更新失败: {msg}")
        except Exception as e:
            if is_interactive:
                InfoBar.error(self.tr("检查更新失败"), self.tr("无法连接到更新服务器或解析响应。 ({0})").format(str(e)), parent=self)
            print(f"检查更新异常: {e}")

    def check_for_updates_interactive(self):
        self.check_for_updates(is_interactive=True)

    def check_for_updates_on_startup(self):
        if cfg.get(cfg.checkUpdateAtStartUp):
            self.check_for_updates(is_interactive=False)

    def open_download_url(self, url_string: str):
        """在默认浏览器中打开下载URL"""
        InfoBar.success(
            self.tr("正在打开下载链接"),
            self.tr("正在打开浏览器下载新版本"),
            duration=3000,
            parent=self.window()
        )
        QDesktopServices.openUrl(QUrl(url_string))
        # 打开链接后关闭主程序
        QTimer.singleShot(1000, QApplication.quit)
        